import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'

Vue.use(VueRouter)

let originPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location, req, res) {
  if (req === 'undefined' || res === 'undefined') {
    return originPush.call(this, location).catch(() => {})
  } else {
    return originPush.call(this, location, req, res)
  }
}
let originReplace = VueRouter.prototype.push
VueRouter.prototype.replace = function (location, req, res) {
  if (req === 'undefined' || res === 'undefined') {
    return originReplace.call(this, location).catch(() => {})
  } else {
    return originReplace.call(this, location, req, res)
  }
}

const router = new VueRouter({
  routes,
  scrollBehavior() {
    return { y: 0 }
  },
})

router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token
  let userInfo = store.state.user.userInfo
  if (token) {
    //用户登录了
    if (to.path === '/login') {
      //用户去的是登录页面
      next('/')
    } else {
      //去的是其他页面
      if (userInfo.name) {
        //用户信息存在
        next()
      } else {
        //用户信息不存在 重新发送请求获取用户信息
        //有可能接收到失败请求
        try {
          await store.dispatch('getUserInfo')
          next()
        } catch (error) {
          //说明token可能已经过期 重新登录获取新token
          await store.dispatch('getLogOut')
          next('/login')
        }
      }
    }
  } else {
    //用户未登录
    if (
      to.path.indexOf('/pay') !== -1 ||
      to.path.indexOf('/center') !== -1 ||
      to.path.indexOf('/trade') !== -1
    ) {
      //去的是登录才有权限进的页面
      next(`/login?wantpath=${to.path}`)
    } else {
      //去的是其余页面
      next()
    }
  }
})

export default router
